package com.qdlc.p2p.biz.sms;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.qdlc.p2p.common.util.DataUtils;
import com.qdlc.p2p.common.util.LogFactory;
import com.qdlc.p2p.common.util.OrderNoUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;

/**
 * 功能描述: 亿美短信发送通道
 * @author linya
 * @date 2016-5-3
 */
public class EmaySmsPortalImpl implements SmsPortal {

	public static Logger log = LogFactory.SMS_LOGGER;
	
	// 软件序列号,请通过亿美销售人员获取(8SDK-EMY-6699-REWUP)
	public static String sn = SystemConfigHelper.getValue(Nid.SMS_USERNAME);
	
	// 序列号首次激活时自己设定(002704)
	public static String key = SystemConfigHelper.getValue(Nid.SMS_PASSWORD);
	
	// 密码,请通过亿美销售人员获取(002704)
	public static String password = SystemConfigHelper.getValue(Nid.SMS_PASSWORD);
	
	// 亿美请求地址(http://hprpt2.eucp.b2m.cn:8080/sdkproxy/)
	public static String baseUrl = SystemConfigHelper.getValue(Nid.USE_SMS_URL);
	
	@Override
	public String getSPName() {
		return "亿美";
	}

	@Override
	public String send(String phone, String content) {
		try {
			String message = URLEncoder.encode(content, "UTF-8");
			String code = "888";
			long seqId = System.currentTimeMillis();
			String param = "cdkey=" + sn + "&password=" + key + "&phone=" + phone + "&message=" + message + "&addserial=" + code + "&seqid=" + seqId;
			String url = baseUrl + "sendsms.action";
			String ret = sendSMS(url, param);
			if(!"0".equals(ret)){
				log.info("++++ [短信发送] 亿美短信通道发送失败:" + ErrorCode.getMessage(ret));
			}
		} catch (Exception e) {
			log.info("++++ [短信发送] 亿美短信通道发送失败!", e);
			e.printStackTrace();
		}
		return null;
	}

    public static String sendSMS(String url, String param) {
		String ret = "";
		url = url + "?" + param;
		String responseString = sendGet(url);
		responseString = responseString.trim();
		if (null != responseString && !"".equals(responseString)) {
		    ret = xmlMt(responseString);
		}
		return ret;
    }
    
    // 解析下发response
    public static String xmlMt(String response) {
		String result = "0";
		Document document = null;
		try {
		    document = DocumentHelper.parseText(response);
		} catch (DocumentException e) {
		    e.printStackTrace();
		    result = "-250";
		}
		Element root = document.getRootElement();
		result = root.elementText("error");
		if (null == result || "".equals(result)) {
		    result = "-250";
		}
		return result;
    }
    
    /**
     * Get请求
     * @param url
     * @return
     */
    public static String sendGet(String url) {
		String result = "";
		BufferedReader in = null;
		try {
		    URL realUrl = new URL(url);
		    // 打开和URL之间的连接
		    URLConnection connection = realUrl.openConnection();
		    // 设置通用的请求属性
		    connection.setRequestProperty("accept", "*/*");
		    connection.setRequestProperty("connection", "Keep-Alive");
		    connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		    // 设置连接超时和读取超时
		    connection.setConnectTimeout(30 * 1000);
		    connection.setReadTimeout(60 * 1000);
		    // 建立实际的连接
		    connection.connect();
	
		    // 定义 BufferedReader输入流来读取URL的响应
		    in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		    String line;
		    while ((line = in.readLine()) != null) {
			result += line;
		    }
		} catch (Exception e) {
		    log.error("Exception is happened!-->" + e.getMessage());
		    result = "-99";
		} finally {
		    try {
			if (in != null) {
			    in.close();
			}
		    } catch (Exception e) {
			log.error("Exception is happened!", e);
		    }
		}
		return result;
    }
    
    private static enum ErrorCode{
    	M_0(0,"成功"),
    	M_1(-1,"系统异常"),
    	M_101(-101,"命令不被支持"),
    	M_102(-102,"RegistryTransInfo删除信息失败"),
    	M_103(-103,"RegistryInfo更新信息失败"),
    	M_104(-104,"请求超过限制"),
    	M_111(-111,"企业注册失败"),
    	M_117(-117,"发送短信失败"),
    	M_118(-118,"接收MO失败"),
    	M_119(-119,"接收Report失败"),
    	M_120(-120,"修改密码失败"),
    	M_122(-122,"号码注销激活失败"),
    	M_110(-110,"号码注册激活失败"),
    	M_123(-123,"查询单价失败"),
    	M_124(-124,"查询余额失败"),
    	M_125(-125,"设置MO转发失败"),
    	M_126(-126,"路由信息失败"),
    	M_127(-127,"计费失败0余额"),
    	M_128(-128,"计费失败余额不足"),
    	M_1100(-1100,"序列号错误,序列号不存在内存中,或尝试攻击的用户"),
    	M_1103(-1103,"序列号Key错误"),
    	M_1102(-1102,"序列号密码错误"),
    	M_1104(-1104,"路由失败，请联系系统管理员"),
    	M_1105(-1105,"注册号状态异常, 未用 1"),
    	M_1107(-1107,"注册号状态异常, 停用 3"),
    	M_1108(-1108,"注册号状态异常, 停止 5"),
    	M_113(-113,"充值失败"),
    	M_1131(-1131,"充值卡无效"),
    	M_1132(-1132,"充值密码无效"),
    	M_1133(-1133,"充值卡绑定异常"),
    	M_1134(-1134,"充值状态无效"),
    	M_1135(-1135,"充值金额无效"),
    	M_190(-190,"数据操作失败"),
    	M_1901(-1901,"数据库插入操作失败"),
    	M_1902(-1902,"数据库更新操作失败"),
    	M_1903(-1903,"数据库删除操作失败");
    	
    	int code;
    	String message;
    	
    	ErrorCode(int code, String message){
    		this.code = code;
    		this.message = message;
    	}
    	
    	public static String getMessage(String code){
    		int c = DataUtils.toInt(code);
    		for(ErrorCode e: ErrorCode.values()){
    			if(c == e.code){
    				return e.message;
    			}
    		}
    		return M_1.message;
    	}
    	
    }
}
